package com.app.mingluxing.db;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.app.mingluxing.utils.Constant;


/**
 * 创建数据库
 * Created by Aaron on 15/12/15.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int VERSION = 1; //数据库版本
    private final SharedPreferences sp;

    public DatabaseHelper(Context context) {
        super(context, Constant.DB_NAME, null, VERSION);

        sp = context.getSharedPreferences(Constant.CONFIG, Context.MODE_PRIVATE);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        //创建 历史记录表(该表保存了所有的聊天记录)
        //_id 主键, sendId 发送人的id, sendName 发送人的昵称, sendPic 发送人的头像, receiverTime 接受消息的时间,
        //isRead , content 消息内容, topic 消息的topic,messageType消息内容的类型(文本,音频等)
        //receiveId 接受人的id, receiveName接受的昵称, receivePic接受人的头像, voiceLength音频时长,
        // chatType 聊天类型(单聊,群聊) userId 用户id
        db.execSQL("CREATE TABLE IF NOT EXISTS " + Constant.HISTORY_TABLE +
                " (_id INTEGER PRIMARY KEY AUTOINCREMENT, sendId VARCHAR, sendName VARCHAR, sendPic VARCHAR," +
                "receiverTime VARCHAR, isRead VARCHAR, content VARCHAR, topic VARCHAR, messageType VARCHAR" +
                ", receiveId VARCHAR, receiveName VARCHAR, receivePic VARCHAR," +
                " voiceLength VARCHAR, chatType VARCHAR, sendTime VARCHAR, userId VARCHAR, isListener VARCHAR)");

        //创建topic表 (该表保存了所有的聊天主题topic, 和改聊天主题的最后一天消息)
        //topic 为主键, topicName 聊天室的名称, topic 聊天的主题, 群聊的时候 receiverPic 存的就是群聊的头像
        Log.e("tag", " topic表名:" + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, ""));
        db.execSQL("CREATE TABLE IF NOT EXISTS " + Constant.TOPIC_TABLE + sp.getString(Constant.USERID, "") +
                " (_id INTEGER , topicName VARCHAR, topic VARCHAR, sendId VARCHAR, " +
                "sendName VARCHAR, sendPic VARCHAR," + "receiverTime VARCHAR, receiveId VARCHAR, content VARCHAR," +
                " messageType VARCHAR, voiceLength VARCHAR, chatType VARCHAR, sendTime VARCHAR, receivePic VARCHAR, " +
                "receiveName VARCHAR, isRead INTEGER, userId VARCHAR, isListener VARCHAR, PRIMARY KEY(topic))");
//default 0
//        LogUtil.e("tag", "数据库表创建成功");

    }

    //数据库版本更新
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        switch (newVersion) {

            case 1:
                break;

            case 2:
                //有新版本要更新,为新表插入一个 VARCHAR 类型的 other字段,
                // 更新时允许用户重命名或添加新的字段到已有表中，但是不能从表中删除字段。并且只能在表的末尾添加字段
                //db.execSQL("ALTER TABLE phistory ADD COLUMN other VARCHAR");
                break;

            default:
                break;

        }

    }
}